import { getComponent } from '../_util/props-util'
import { computed, defineComponent, ref, createTextVNode } from 'vue'

import inputProps from './inputProps'

import Button from '../button'
import Input from './input'

const prefixCls = 'x-input-search'

export default defineComponent({
  name: prefixCls,
  components: { Button, Input },
  props: {
    ...inputProps,
    enterButton: String || Boolean
  },
  setup(props, { attrs, emit, expose, slots }) {

    const showBtn = computed(() => !!props.enterButton || props.enterButton === '' || !!slots.enterButton)
    const btnText = computed(() => {
      let text = '🔍'
      if (typeof props.enterButton === 'string') {
        text = props.enterButton || text
      }
      return text
    })
    const btnIcon = computed(() => {
      if (props.enterButton === '') return 'search'
      if (props.enterButton === true) return 'search'
    })
    const inputRef = ref<HTMLInputElement>()

    function onSearch() {
      emit('search', inputRef.value.value)
      inputRef.value.focus()
    }


    expose({
      focus() { inputRef.value.focus() },
      blur() { inputRef.value.blur() },
      get value() { return inputRef.value.value }
    })

    
    return vm => {
      const cls = [prefixCls, {
        [`${prefixCls}-enter`]: showBtn.value
      }]

      let enterNode = showBtn.value && (getComponent(vm, 'enterButton') || <Button type="primary">{ btnText.value }</Button>)
      if (!enterNode) enterNode = createTextVNode('🔍')
      enterNode = <div class={`${prefixCls}_enter`} onClick={onSearch}>{ enterNode }</div>

      return (
        <Input class={cls} ref={inputRef} {...{...props, ...attrs}} onPressEnter={onSearch}>
          {{
            addonAfter: () => showBtn.value && enterNode,
            suffix: () => !showBtn.value && enterNode
          }}
        </Input>
      )
    }
  }
})